<template>
  <div>
    <el-breadcrumb separator="|">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 工具栏 -->
    <div class="toolBar">
      <el-button type="primary" plain @click="showSave">添加</el-button>
      名称：<el-input
        label="关键字"
        v-model="keyword"
        placeholder="请输入文章名称"
        size="medium"
        @input="pageIndex = 1"
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </div>
    <!-- 数据表格 -->
    <el-table :data="ArticleList" style="width: 100%" v-loading="loading">
      <el-table-column prop="Cover" label="封面" width="200">
        <template slot-scope="scope">
          <img :src="scope.row.Cover" v-if="scope.row.Cover" height="30px" />
        </template>
      </el-table-column>
      <el-table-column prop="Title" label="标题"> </el-table-column>
      <el-table-column prop="CategoryId" label="分类"> </el-table-column>
      <el-table-column prop="TagName" label="标签"> </el-table-column>
      <el-table-column prop="Summary" label="摘要"> </el-table-column>
      <el-table-column width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showComment(scope.row)">
            查看
          </el-button>
          <el-button type="text" @click="updateArticle(scope.row)">
            修改
          </el-button>
          <el-button type="text" @click="delArticle(scope.row.Id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="selectList.length"
      :page-size="7"
      @current-change="changePages"
      :current-page="pageIndex"
    >
    </el-pagination>
    <!-- 上传数据 -->
    <el-dialog title="添加文章" :visible.sync="dialogFormVisible" fullscreen>
      <el-form v-model="form" label-position="top">
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8080/Article/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.coverUrl" :src="form.coverUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.Category" placeholder="请选择">
            <el-option
              v-for="item in CategoryList"
              :key="item.Id"
              :value="item.Id"
              :label="item.Name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="form.Label" multiple placeholder="请选择">
            <el-option
              v-for="item in LabelList"
              :key="item.Id"
              :value="item.Id"
              :label="item.Name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.Title"></el-input>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="form.Summary"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              mode="simple"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="form.Content"
              :defaultConfig="editorConfig"
              mode="simple"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input-number
            v-model="form.LikeCount"
            :disabled="true"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="浏览量">
          <el-input-number
            v-model="form.ViewCount"
            :disabled="true"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="saveArticle"> 确 定 </el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改文章" :visible.sync="dialogUpdateVisible">
      <el-form v-model="updateForm">
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8080/Article/updateImg"
            :show-file-list="false"
            :on-success="handleUpdateSuccess"
          >
            <img
              v-if="updateForm.Cover"
              :src="updateForm.Cover"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="updateForm.CategoryId" placeholder="请选择">
            <el-option
              v-for="item in CategoryList"
              :key="item.Id"
              :value="item.Id"
              :label="item.Name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="updateForm.TagName" multiple placeholder="请选择">
            <el-option
              v-for="item in LabelList"
              :key="item.Id"
              :value="item.Id"
              :label="item.Name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="updateForm.Title"></el-input>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="updateForm.Summary"></el-input>
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input-number v-model="updateForm.LikeCount"></el-input-number>
        </el-form-item>
        <el-form-item label="浏览量">
          <el-input-number v-model="updateForm.ViewCount"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdateVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="saveUpdate"> 确 定 </el-button>
      </div>
    </el-dialog>
    <!-- 查看文章 -->
    <el-dialog :visible.sync="dialogViewVisible" fullscreen> 
      <h1>{{viewForm.Title}}</h1>
      <hr>
      <div v-html="viewForm.Content"></div>
       </el-dialog>
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
  name: "ArticlePart",
  components: {
    Editor,
    Toolbar,
  },
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      loading: true,
      keyword: "",
      dialogViewVisible: false,
      dialogFormVisible: false,
      dialogUpdateVisible: false,
      list: [],
      pageIndex: 1,
      form: {
        coverUrl: "",
        CategoryId: "",
        Label: "",
        Title: "",
        Summary: "",
        Content: "",
        LikeCount: "0",
        ViewCount: "0",
      },
      updateForm: {
        Cover: "",
        Category: "",
        TagName: "",
        Title: "",
        Summary: "",
        Content: "",
        LikeCount: "",
        ViewCount: "",
      },
      viewForm: {
        Title: "",
        Content: "",
      },
      CommentList: [],
      CategoryList: [],
      LabelList: [],
      TapList: [],
    };
  },
  computed: {
    selectList() {
      return this.list.filter((p) => {
        return p.Title.indexOf(this.keyword) != -1;
      });
    },
    ArticleList() {
      let startNum = (this.pageIndex - 1) * 7;
      let endNum = this.pageIndex * 7;
      return this.selectList.slice(startNum, endNum);
    },
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    //打开添加
    showSave() {
      this.dialogFormVisible = true;
      this.form = {
        coverUrl: "",
        CategoryId: "",
        Label: "",
        Title: "",
        Summary: "",
        Content: "",
        LikeCount: "0",
        ViewCount: "0",
      };
    },
    //获取文章数据
    getArticle() {
      this.loading = true;
      this.axios
        .get("http://127.0.0.1:8080/Article/Article")
        .then((res) => {
          //遍历服务器返回的每一条tag数据
          for (let i = 0; i < res.data.TagData[0].length; i++) {
            //取出每一个TagId
            let tmpTagId = res.data.TagData[0][i].TagId.split(",");
            for (let x = 0; x < this.LabelList.length; x++) {
              for (let y = 0; y < tmpTagId.length; y++) {
                //当取出的TagId与LabelList中的某一个id相同，则将该id所对应的名字进行替换
                if (this.LabelList[x].Id == tmpTagId[y]) {
                  tmpTagId[y] = this.LabelList[x].Name;
                }
              }
            }
            //将替换名字之后的数据添加给TapList
            this.TapList.push(tmpTagId);
          }
          for (let i = 0; i < res.data.data[0].length; i++) {
            this.$set(res.data.data[0][i], "TagName", this.TapList[i]);
            for (let x = 0; x < this.CategoryList.length; x++) {
              if (this.CategoryList[x].Id == res.data.data[0][i].CategoryId) {
                res.data.data[0][i].CategoryId = this.CategoryList[x].Name;
              }
            }
          }
          this.list = res.data.data[0];
          this.loading = false;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //保存文章数据
    saveArticle() {
      this.loading = true;
      this.axios({
        method: "post",
        url: "http://127.0.0.1:8080/Article/add",
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        params: {
          form: this.form,
        },
      })
        .then((res) => {
          this.$message({
            message: res.data,
            type: "success",
          });
          this.getArticle();
        })
        .catch((err) => {
          console.log("err", err);
        });
      this.dialogFormVisible = false;
    },
    //删除文章数据
    delArticle(id) {
      this.loading = true;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .post(
              "http://127.0.0.1:8080/Article/del",
              {},
              {
                headers: {
                  "content-type": "application/x-www-form-urlencoded",
                },
                params: {
                  id: id,
                },
              }
            )
            .then((res) => {
              this.$message({
                type: "success",
                message: res.data,
              });
              this.getArticle();
              this.pageIndex = 1;
            })
            .catch((err) => {
              console.error(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.loading = false;
        });
      this.getArticle();
    },
    //修改
    updateArticle(row) {
      this.dialogUpdateVisible = true;
      let tmpRow = JSON.parse(JSON.stringify(row));
      for (let i = 0; i < this.CategoryList.length; i++) {
        if (tmpRow.CategoryId == this.CategoryList[i].Name) {
          tmpRow.CategoryId = this.CategoryList[i].Id;
        }
      }
      for (let i = 0; i < this.LabelList.length; i++) {
        for (let x = 0; x < tmpRow.TagName.length; x++) {
          if (this.LabelList[i].Name == tmpRow.TagName[x]) {
            tmpRow.TagName[x] = this.LabelList[i].Id;
          }
        }
      }
      this.updateForm = tmpRow;
    },
    //保存修改
    saveUpdate() {
      this.loading = true;
      this.axios({
        method: "post",
        url: "http://127.0.0.1:8080/Article/update",
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        params: {
          data: this.updateForm,
        },
      })
        .then((res) => {
          this.$message({
            message: res.data,
            type: "success",
          });
          this.getArticle();
        })
        .catch((err) => {
          console.log("err", err);
        });
      this.dialogUpdateVisible = false;
      this.getArticle();
    },
    //改变当前页数
    changePages(index) {
      this.pageIndex = index;
    },
    //上传封面成功
    handleAvatarSuccess(res) {
      this.form.coverUrl = res;
    },
    //上传修改封面成功
    handleUpdateSuccess(res) {
      this.updateForm.Cover = res;
    },
    //获取分类数据
    getCategory() {
      this.axios
        .get("http://127.0.0.1:8080/Category/Category")
        .then((res) => {
          this.CategoryList = res.data.recordset;
          this.loading = false;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //获取标签数据
    getLabel() {
      this.axios
        .get("http://127.0.0.1:8080/Label/Label")
        .then((res) => {
          this.LabelList = res.data.recordset;
          this.loading = false;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //获取文章数据
    getComment() {
      this.axios.get("http://127.0.0.1:8080/Article/Comment").then((res) => {
        this.CommentList = res.data.recordset;
      });
    },
    //查看
    showComment(row) {
      this.dialogViewVisible = true;
      this.viewForm.Title = row.Title;
      this.CommentList.forEach((element) => {
        if (element.ArticleId === row.Id) {
          this.viewForm.Content = element.Content;
        }
      });
    },
  },
  mounted() {
    this.getLabel();
    this.getCategory();
    this.getArticle();
    this.getComment();
  },
};
</script>

<style lang="less" scoped>
.toolBar {
  padding: 10px;
}
.el-input {
  width: 300px;
}
.el-pagination {
  position: absolute;
  bottom: 20px;
  left: 50%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>